#include "datetimeui.h"
#include <QApplication>

DatetimeUi::DatetimeUi()
{
    setAttribute(Qt::WA_DeleteOnClose);
    uiLayout            = new QVBoxLayout(this);
    currentDateLayout   = new QVBoxLayout(this);
    otherTimezoneLayout = new QVBoxLayout(this);
    uiLayout->addLayout(currentDateLayout);
    uiLayout->addLayout(otherTimezoneLayout);
    uiLayout->addStretch();
    uiLayout->setSpacing(40);
    uiLayout->setMargin(0);
    currentDateLayout->setSpacing(8);
    initUi();
}

DatetimeUi::~DatetimeUi()
{

}

void DatetimeUi::initUi()
{
    initObject();
    initCurrentDate();
    initOtherTimezone();
    initSignals();
}

void DatetimeUi::initObject()
{
    // 当前时间
    currentTitleLabel = new TitleLabel(this); // 标题
    clockWidget       = new ClockWidget(); // 时钟
    timeLabel         = new TimeLabel(this); // 时间
    mDateLabel        = new FixLabel(this); // 日期
    changeTZbutton    = new FixButton(this); // 修改时区
    setTimeModeLabel  = new FixLabel(this);  // 设置时间
    manualRadioButton = new QRadioButton(this); // 手动设置时间
    syncRadioButton   = new QRadioButton(this); // 自动同步时间
    syncResultLabel   = new FixLabel(); // 同步时间结果
    setDateLabel      = new FixLabel(this); // 手动设置日期
    dategroupWidget   = new DategroupWidget(this);
    timeBtnGroup      = new QButtonGroup(this);
    //~ contents_path /Date/Sync Server
    ntpSerWidget      = new ComboxWidget(tr("Sync Server"), this);
    setNtpLabel       = new FixLabel(this);
    setNtpLineEdit    = new QLineEdit(this);
    setNtpButton      = new FixButton(this);

    timeBtnGroup->addButton(manualRadioButton, 0);
    timeBtnGroup->addButton(syncRadioButton, 1);
    syncResultLabel->setStyleSheet("QLabel{color: #D9F82929;}");

    otherTimezoneTitleLabel = new TitleLabel(this);
    addTimezoneButton       = new AddButton(this, UkccFrame::BorderRadiusStyle::Around);
}

void DatetimeUi::initCurrentDate()
{
    SettingGroup *currentDateGroup  = new SettingGroup(this);
    UkccFrame    *clockFrame        = new UkccFrame(currentDateGroup);
    UkccFrame    *setTimeFrame      = new UkccFrame(currentDateGroup, UkccFrame::BorderRadiusStyle::Around, true);
    UkccFrame    *setDateFrame      = new UkccFrame(currentDateGroup, UkccFrame::BorderRadiusStyle::Around, true);
    UkccFrame    *ntpAddressFrame   = new UkccFrame(currentDateGroup, UkccFrame::BorderRadiusStyle::Around, true);

    //~ contents_path /Date/Current Date
    currentTitleLabel->setText(tr("Current Date"));
    currentDateLayout->addWidget(currentTitleLabel);
    currentDateLayout->addWidget(currentDateGroup);
    currentDateGroup->addWidget(clockFrame);
    currentDateGroup->addWidget(setTimeFrame);
    currentDateGroup->addWidget(setDateFrame);
    currentDateGroup->addWidget(ntpSerWidget);
    currentDateGroup->addWidget(ntpAddressFrame);

    QHBoxLayout *clockLayout      = new QHBoxLayout(clockFrame);
    UkccFrame   *clockRightFrame  = new UkccFrame(clockFrame);
    QVBoxLayout *clockRightLayout = new QVBoxLayout(clockRightFrame);
    UkccFrame   *dataZoneFrame    = new UkccFrame(clockRightFrame);
    QHBoxLayout *dataZoneLayout   = new QHBoxLayout(dataZoneFrame);
    clockLayout->addWidget(clockWidget);
    clockLayout->addWidget(clockRightFrame);
    clockLayout->setSpacing(26);
    clockRightLayout->setMargin(0);
    clockRightLayout->addWidget(timeLabel);
    clockRightLayout->addWidget(dataZoneFrame);
    dataZoneLayout->setMargin(0);
    dataZoneLayout->setSpacing(16);
    dataZoneLayout->addWidget(mDateLabel);
    dataZoneLayout->addWidget(changeTZbutton);
    dataZoneLayout->addStretch();
    clockFrame->setFixedHeight(156);
    clockRightFrame->setFixedHeight(102);
    changeTZbutton->setFixedWidth(150);
    //~ contents_path /Date/Timezone
    changeTZbutton->setText(tr("Timezone"));

    QHBoxLayout *setTimeLayout = new QHBoxLayout(setTimeFrame);
    QSpacerItem *setTimeSpacer = new QSpacerItem(10, 24, QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed);
    setTimeModeLabel->setFixedWidth(136);
    //~ contents_path /Date/Set Time
    setTimeModeLabel->setText(tr("Set Time"));
    //~ contents_path /Date/Manual Time
    manualRadioButton->setText(tr("Manual Time"));
    //~ contents_path /Date/Sync Time
    syncRadioButton->setText(tr("Sync Time"));
    setTimeLayout->setContentsMargins(16, 0, 0, 0);
    setTimeLayout->setSpacing(16);
    setTimeLayout->addWidget(setTimeModeLabel);
    setTimeLayout->addWidget(manualRadioButton);
    setTimeLayout->addSpacerItem(setTimeSpacer);
    setTimeLayout->addWidget(syncRadioButton);
    setTimeLayout->addWidget(syncResultLabel);
    setTimeLayout->addStretch();

    QHBoxLayout *setDateLayout  = new QHBoxLayout(setDateFrame);
    //~ contents_path /Date/Set Date Manually
    setDateLabel->setText(tr("Set Date Manually"));
    setDateLabel->setFixedWidth(136);
    setDateLayout->setSpacing(16);
    setDateLayout->setContentsMargins(16, 0, 0, 0);
    setDateLayout->addWidget(setDateLabel);
    setDateLayout->addWidget(dategroupWidget);

    connect(timeLabel, &TimeLabel::dateChanged, mDateLabel, [=](){
        updateDate();
    });
    connect(timeBtnGroup, QOverload<int, bool>::of(&QButtonGroup::buttonToggled), this, [=](int id, bool clicked){
        if ((id == 0 && clicked) || (id == 1 && !clicked)) {
            ntpAddressFrame->hide();
            ntpSerWidget->hide();
            setDateFrame->show();
        } else {
            setDateFrame->hide();
            ntpSerWidget->show();
            if (ntpSerWidget->comboBox()->currentIndex() == (ntpSerWidget->comboBox()->count() - 1)) {
                ntpAddressFrame->show();
            } else {
                ntpAddressFrame->hide();
            }
            qApp->processEvents();
        }
    });

    ntpSerWidget->setTitleFixedWidth(136);
    QHBoxLayout *ntpAddresslayout = new QHBoxLayout(ntpAddressFrame);
    ntpAddresslayout->setContentsMargins(16, 8, 16, 8);
    ntpAddresslayout->setSpacing(16);
    ntpAddresslayout->addWidget(setNtpLabel);
    ntpAddresslayout->addWidget(setNtpLineEdit);
    ntpAddresslayout->addWidget(setNtpButton);
    setNtpLabel->setText(tr("Server Address"));
    setNtpLabel->setFixedWidth(136);
    setNtpLineEdit->setPlaceholderText(tr("Required"));
    setNtpButton->setText(tr("Save"));
    setNtpButton->setEnabled(false); // 初始状态不可点击

    connect(ntpSerWidget->comboBox(), &QComboBox::currentTextChanged, this, [=](QString text){
        if (text == tr("Customize") && !ntpSerWidget->isHidden()) {
            setNtpLineEdit->clear();
            ntpAddressFrame->show();
        } else {
            ntpAddressFrame->hide();
        }
    });
    connect(setNtpLineEdit, &QLineEdit::textChanged, this, [=](){
        setNtpLineEdit->blockSignals(true);
        while (setNtpLineEdit->text().front() == " ") {
            setNtpLineEdit->setText(setNtpLineEdit->text().remove(0, 1)); //去掉首空格
        }
        setNtpLineEdit->blockSignals(false);
        setNtpButton->setEnabled(!setNtpLineEdit->text().isEmpty());   //为空时不允许保存
    });
}

void DatetimeUi::initOtherTimezone()
{
    //~ contents_path /Date/Other Timezone
    otherTimezoneTitleLabel->setText(tr("Other Timezone"));
    otherTimezoneLayout->setSpacing(0);
    otherTimezoneLayout->addWidget(otherTimezoneTitleLabel);
    otherTimezoneLayout->addSpacing(8);
    otherTimezoneLayout->addWidget(addTimezoneButton);
    otherTimezoneLayout->addStretch();
}

void DatetimeUi::initSignals()
{
    connect(dategroupWidget, &DategroupWidget::dateChanged, this, &DatetimeUi::dateTimeChanged);
    connect(timeBtnGroup, QOverload<int>::of(&QButtonGroup::buttonClicked), this, [=](int id){
        if (id == 0) {
            syncResultLabel->setPixmap(QPixmap(""));
            syncResultLabel->setText("");
            Q_EMIT timeModeChanged("manual");
        } else {
            Q_EMIT timeModeChanged("automatic");
        }
    });
    connect(changeTZbutton, &FixButton::clicked, this, &DatetimeUi::timezoneButtonClicked);
    connect(ntpSerWidget->comboBox(), QOverload<const QString&>::of(&QComboBox::activated), this, [=](QString server){
        if (ntpSerWidget->comboBox()->currentIndex() == 0) {
            server = "default";
            Q_EMIT ntpServerChanged(server);
        } else if (ntpSerWidget->comboBox()->currentIndex() == ntpSerWidget->comboBox()->count() - 1) {

        } else {
            Q_EMIT ntpServerChanged(server);
        }
    });
    connect(setNtpButton, &FixButton::clicked, this, [=](){
        Q_EMIT ntpServerChanged(setNtpLineEdit->text());
    });
    connect(addTimezoneButton, &AddButton::clicked, this, &DatetimeUi::addTimezoneButtonClicked);
}

void DatetimeUi::updateDate()
{
    QString dateStr = timeLabel->dateText();
    if (!dateStr.isEmpty() && !timezoneStr.isEmpty()) {
        mDateLabel->setText(dateStr + "  " + timezoneStr);
    }
}

void DatetimeUi::setTimeMode(QString mode)
{
    if (mode == "manual") {
        manualRadioButton->setChecked(true);
    } else {
        syncRadioButton->setChecked(true);
    }
}

void DatetimeUi::setSyncResultLabel(int flag)
{
    if (flag == 0) { // 失败，显示图标
        static quint32 times = 0;
        quint8 picNum = times - qFloor(times/8)*8; //限制在0~7
        QString pixName = QString(":/images/loading%1.svg").arg(picNum+10);
        QPixmap pix(pixName);
        qApp->processEvents();
        syncResultLabel->setText("");
        syncResultLabel->setPixmap(pix);
        times++;
    } else if (flag == 1) { // 失败，显示文字
        syncResultLabel->setPixmap(QPixmap(""));
        syncResultLabel->setText(tr("Sync failed"));
    } else {
        syncResultLabel->setPixmap(QPixmap("")); //成功，不显示任何内容
        syncResultLabel->setText("");
    }
}

void DatetimeUi::setNtpServers(QStringList sl)
{
    ntpSerWidget->comboBox()->clear();
    sl.insert(0, tr("Default"));
    sl.append(tr("Customize"));
    ntpSerWidget->comboBox()->addItems(sl);
}

void DatetimeUi::setNtpServer(QString s)
{
    if (s.isEmpty()) { // 系统默认
        ntpSerWidget->setCurrentIndex(0);
    } else {
        bool isContains = false;
        for (int i = 1; i < ntpSerWidget->comboBox()->count() - 1; ++i) {
            if (ntpSerWidget->comboBox()->itemText(i) == s) {
                ntpSerWidget->setCurrentIndex(i);
                isContains = true; // 列表中
                break;
            }
        }
        if (!isContains) { // 自定义
            ntpSerWidget->setCurrentIndex(ntpSerWidget->comboBox()->count() - 1);
            setNtpLineEdit->blockSignals(true);
            setNtpLineEdit->setText(s);
            setNtpLineEdit->blockSignals(false);
        }
    }
}

void DatetimeUi::setTimezoneStr(QString str)
{
    timezoneStr = str;
    updateDate();
}

void DatetimeUi::addOtherTimezone(const QString &timezone, const QString &timezoneName)
{
    TimeBtn *timeBtn = new TimeBtn(timezone, timezoneName);
    QSpacerItem *spaceIterm = new QSpacerItem(1, 1, QSizePolicy::Fixed, QSizePolicy::Fixed);
    int index = otherTimezoneLayout->count() - 2; // button and Stretch
    otherTimezoneLayout->insertWidget(index, timeBtn);
    otherTimezoneLayout->insertSpacerItem(index + 1, spaceIterm);
    connect(timeBtn, &TimeBtn::deleted, this, [=](){
        otherTimezoneLayout->removeItem(spaceIterm);
        delete spaceIterm;
        Q_EMIT timezoneRemoved(timezone);
    });
}

void DatetimeUi::setAddTimezoneBtnEnabled(bool b)
{
    addTimezoneButton->setEnabled(b);
}
